package com.sky.service.impl;

import com.sky.dto.MerchantCategoryDTO;
import com.sky.entity.MerchantCategory;
import com.sky.mapper.MerchantCategoryMapper;
import com.sky.mapper.MerchantMapper;
import com.sky.service.MerchantCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 商家分类服务实现类
 */
@Service
public class MerchantCategoryServiceImpl implements MerchantCategoryService {
    
    @Autowired
    private MerchantCategoryMapper merchantCategoryMapper;
    
    @Autowired
    private MerchantMapper merchantMapper; // 用于检查分类是否被使用
    
    @Override
    public List<MerchantCategory> getAllMerchantCategories() {
        return merchantCategoryMapper.selectAll();
    }
    
    @Override
    public MerchantCategory getMerchantCategoryById(Integer id) {
        return merchantCategoryMapper.selectById(id);
    }
    
    @Override
    public MerchantCategory createMerchantCategory(MerchantCategoryDTO merchantCategoryDTO) {
        // 创建分类实体
        MerchantCategory merchantCategory = new MerchantCategory();
        BeanUtils.copyProperties(merchantCategoryDTO, merchantCategory);
        
        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        merchantCategory.setCreatedAt(now);
        merchantCategory.setUpdatedAt(now);
        
        // 保存到数据库
        merchantCategoryMapper.insert(merchantCategory);
        
        return merchantCategory;
    }
    
    @Override
    public MerchantCategory updateMerchantCategory(Integer id, MerchantCategoryDTO merchantCategoryDTO) {
        // 检查分类是否存在
        MerchantCategory existingCategory = merchantCategoryMapper.selectById(id);
        if (existingCategory == null) {
            throw new RuntimeException("分类不存在");
        }
        
        // 更新分类信息
        BeanUtils.copyProperties(merchantCategoryDTO, existingCategory);
        existingCategory.setUpdatedAt(LocalDateTime.now());
        
        // 保存更新
        merchantCategoryMapper.update(existingCategory);
        
        return existingCategory;
    }
    
    @Override
    public void deleteMerchantCategory(Integer id) {
        // 检查分类是否存在
        MerchantCategory category = merchantCategoryMapper.selectById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }
        
        // 检查分类是否被商家使用
        // 这里假设MerchantMapper中有方法检查分类是否被使用
        // 可以在实际实现中添加相应的查询方法
        // boolean isUsed = merchantMapper.checkCategoryUsed(id);
        // if (isUsed) {
        //     throw new RuntimeException("该分类已被使用，无法删除");
        // }
        
        // 删除分类
        merchantCategoryMapper.deleteById(id);
    }
}